/*jslint browser: true*/
/*global $, jQuery, alert, window*/

/*根据user_id，查找user_name*/
window.creater_id_name = function (user_id) {
    "use strict";
    var author_list = window.fetchData(window.storage("/user/"), window.format.author),
        index,
        length = author_list.length,
        author_item;
    window.creater_id_name = function (user_id) {
        for (index = 0; index < length; index = index + 1) {
            author_item = author_list[index];
            if (author_item.id === user_id) {
                return author_item.name;
            }
        }
        return "";
    };
    return window.creater_id_name(user_id);
};

window.view = {
    "questin_id" : function (value) {
        "use strict";
        //set and get
        if (value) {
            $("#questin_id").val(value);
        }
        return parseInt($("#questin_id").val(), 10);
    },
    "keyword" : function (value) {
        "use strict";
        //set and get
        if (value) {
            $("#keyword").val(value);
        }
        return $("#keyword").val();
    },
    "create_time" : function () {
        "use strict";
        //get
        return window.date_to_int($("#create_time").val());
    },
    "major_id": function (id_string) {
        "use strict";
        //set and get
        if (id_string) {
            $("#major_selection option[value=" + id_string + "]")[0].selected = true;
        }
        return parseInt($("#major_selection").val(), 10);
    },
    "char_id_list": function (id_list) {
        "use strict";
        var treeObj,
            index,
            length,
            char_list;
        //set and get
        if (id_list) {
            $("#char_selection").val(id_list.join(","));
            window.sync.charChecked_select_ztree();
        } else {
            //"".split(",") ==> [""]
            if (!$("#char_selection").val()) { return []; }
            char_list =  $("#char_selection").val().split(",");
            length = char_list.length;
            for (index = 0; index < length; index = index + 1) {
                char_list[index] = parseInt(char_list[index], 10);
            }
            return char_list;
        }
    },
    "author_id": function () {
        "use strict";
        //get
        var author_list = window.fetchData(window.storage("/user/"), window.format.author),
            name_value = $("#author").val(),
            index,
            length = author_list.length,
            author_item;
        for (index = 0; index < length; index = index + 1) {
            author_item = author_list[index];
            if (author_item.name === name_value) {
                return author_item.id;
            }
        }
        return 0;
    },
    "category_num": function (category_num_value) {
        "use strict";
        //set and get
        if (category_num_value) {
            $("#category option[value=" + category_num_value + "]")[0].selected = true;
        }
        return parseInt($("#category").val(), 10);
    },
    "level_num": function (level_num_value) {
        "use strict";
        //set and get
        if (level_num_value) {
            $("#level option[value=" + level_num_value + "]")[0].selected = true;
        }
        return parseInt($("#level").val(), 10);
    }
};

window.sync = {
    "char_data_ztree": function () {
        "use strict";
        var major_id = window.view.major_id(),
            char_list_key = '/major/{major_id}/char/'.format({major_id: major_id}),
            char_list = window.fetchData(window.storage(char_list_key), window.format.char),
            index,
            length = char_list.length,
            char_item,
            zNodes = [],
            setting = {
                check: { enable: true  },
                data: {
                    simpleData: { enable: true }
                }
            };
        /*
            data :[ { "id": 1, "name":"", "father_id":0, "is_kp":false, "listorder":""}, 
                    { "id": 2, "name":"", "father_id":0, "is_kp":false, "listorder":""},]}
        zNodes =[   { id:13, pId:1, name:"禁止拖拽 1-3", isParent:true },
                    { id:131, pId:13, name:"禁止拖拽 1-3-1", isParent:true },]
        }*/
        for (index = 0; index < length; index = index + 1) {
            char_item = char_list[index];
            zNodes.push({
                id : char_item.id,
                pId : char_item.father_id,
                name : char_item.name,
                isParent : !char_item.is_kp,
                nocheck: !char_item.is_kp,
                open: true
            });
        }
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
    },
    "charChecked_ztree_select" : function () {
        "use strict";
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
            nodes = treeObj.getCheckedNodes(true),
            aList = [],
            index,
            length = nodes.length;
        for (index = 0; index < length; index = index + 1) {
            aList.push(nodes[index].id);
        }
        $("#char_selection").val(aList.join(","));
    },
    "charChecked_select_ztree": function () {
        "use strict";
        //"".split(",") ==> [""]
        if (!$("#char_selection").val()) { return; }
        var checked_id_list = $("#char_selection").val().split(","),
            treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
            index,
            length = checked_id_list.length;
        //zTree
        treeObj.treeObj.checkAllNodes(false);
        for (index = 0; index < length; index = index + 1) {
            treeObj.checkNode(treeObj.getNodeByParam("id", checked_id_list[index]));
        }
    },
    "author_data_options": function () {
        "use strict";
        var author_list = window.fetchData(window.storage("/user/"), window.format.author),
            index,
            length = author_list.length,
            author_item,
            option_list = [];
        for (index = 0; index < length; index = index + 1) {
            author_item = author_list[index];
            option_list.push('<option value="{name}">{id}</option>'.format({name: author_item.name,
                                                                           id: author_item.id}));
        }
        $("#author_list").html("");
        $(option_list.join("")).appendTo("#author_list");
    },
    "major_data_options": function () {
        "use strict";
        var major_list = window.fetchData(window.storage("/major/"), window.format.major),
            index,
            length = major_list.length,
            major_item,
            optionList = [];
        for (index = 0; index < length; index = index + 1) {
            //data :[ { id: 1, name: "string", }, { id: 1, name: "string", },
            major_item = major_list[index];
            optionList.push('<option id="');
            optionList.push("major_" + major_item.id);
            optionList.push('" value="');
            optionList.push(major_item.id);
            optionList.push('">');
            optionList.push(major_item.name);
            optionList.push('</option>');
        }
        $(optionList.join("")).appendTo("#major_selection");
    },
    "question_data_table": function (question_list) {
        "use strict";
        var index,
            length = question_list.length,
            question_item,
            html_list = [],
            category_list = window.category_list,
            level_list = window.level_list,
            user_list = [];
        $("#result_list").html('<tr> <th><input type="checkbox"></th> ' +
                                "<th>ID</th><th>试题类型</th><th>试题摘要</th>" +
                                "<th>试题数</th><th>录入人</th><th>录入时间</th><th>难度</th>" +
                                "<th>操作</th></tr>");
        if (length === 0) {
            $('<tr><td colspan="8" style="height:180px;"> 无此试题 </td></tr>').appendTo("#result_list");
            
        }
        for (index = 0; index < length; index = index + 1) {
            html_list = [];
            question_item = question_list[index];
            html_list.push('<tr><td><input type="checkbox"></td>');
            html_list.push('<td>{id}</td>'.format({
                id: question_item.id
            }));
            html_list.push('<td>{category}</td>'.format({
                category: category_list[question_item.category_num - 1]
            }));
            html_list.push('<td>{tip}</td>'.format({
                tip: question_item.description || ""
            }));
            html_list.push('<td>{sub_num}</td>'.format({
                sub_num: question_item.sub_num
            }));
            html_list.push('<td>{author}</td>'.format({
                author: window.creater_id_name(question_item.creater_id)
            }));
            html_list.push('<td>{timestamp}</td>'.format({
                timestamp: window.int_to_date(question_item.timestamp)
            }));
            html_list.push('<td>{level}</td>'.format({
                level: level_list[question_item.level_num - 1]
            }));
            html_list.push('<td><a target="_blank" href="/manager/question/{category}/{id}/"><div></div></a></td></tr>'.format({
                category: category_list[question_item.category_num - 1],
                id: question_item.id
            }));
            $(html_list.join("")).appendTo("#result_list");
        }
    }
};

window.init = {
    "global_var": function () {
        "use strict";
        jQuery.browser = {};
        jQuery.browser.msie = false;
        $('#create_time').jdPicker({
            month_names : ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
        });
    },
    "onload": function () {
        "use strict";
        var aOffset = $("#char_selection").offset();
        $("#zTreeContainer").css("top", aOffset.top + "px");
        $("#zTreeContainer").css("left", aOffset.left + "px");
        $("#zTreeContainer").css("width", $("#char_selection").width() + "px");
        //event
        $("#major_selection").change(function () {
            window.loading();
            window.view.char_id_list([]);
            var major_id = window.view.major_id(),
                char_list_key = "/major/" + major_id + "/char/";
            window.storage(char_list_key);
            window.sync.char_data_ztree();
            window.hideLoading();
        });
        $("#char_selection").click(function () {
            if ($("#treeDemo").children().length) {
                $("#char_selection").blur();
                $("#zTreeContainer").show("normal");
            }
        });
        $("#zTreeContainer").mouseleave(function () {
            window.sync.charChecked_ztree_select();
            $("#zTreeContainer").hide("normal");
        });
        $("#search_submit").click(function () {
            window.loading();
            var data = {
                    id : window.view.questin_id(),
                    author_id: window.view.author_id(),
                    major_id: window.view.major_id(),
                    char_id_list: window.view.char_id_list(),
                    category_num: window.view.category_num(),
                    level_num: window.view.level_num(),
                    description: window.view.keyword() || null,
                    timestamp: window.view.create_time()
                },
                search_key = "/question/";
            $.ajax({
                url: search_key,
                type: "PUT",
                dataType: "json",
                async: false,
                data: JSON.stringify(data),
                success: function (result, status) {
                    var question_list = window.fetchData(result.data, window.format.question);
                    window.sync.question_data_table(question_list);
                    window.hideLoading();
                }
            });
        });
        //init action
        window.storage("/major/");
        window.sync.major_data_options();
        window.sync.char_data_ztree();
        window.storage("/user/");
        window.sync.author_data_options();
        window.hideLoading();
    }
};
window.init_func_list = ["global_var",
                         "onload"];